<template>
    <div class="roomLicenseBox">
        <div class="tableSetBtn">
            <!-- 刷新列表按钮 -->
            <Button type="primary" style="float: left" @click="refresh(true)" v-if="!isFromRenter">刷新列表</Button>

            <!-- 获取临时密码按钮 -->
            <Button type="primary" style="margin-right:-3px" @click="getPwddayjsVisible = true" v-if="!isFromRenter">获取临时密码</Button>

            <!-- 新增授权（租客界面的或者没有新增授权的权限不显示button） -->
            <Button type="primary" @click="addLicense" v-if="!isFromRenter || !rolePermission['auth_add']">新增授权</Button>

            <!-- 房间标题 -->
            <p class="title" v-if="isFromRenter">房间:{{roomName}}</p>
        </div>

        <!--<Form :model="searchCondition" inline>
            <FormItem>
                <Select v-model="searchCondition.addType" placeholder="授权方式" style="width: 200px">
                    <Option :value="1" :key="1">密码</Option>
                    <Option :value="1" :key="2">蓝牙</Option>
                    <Option :value="1" :key="3">指纹</Option>
                </Select>
            </FormItem>

            <FormItem>
                <Select v-model="searchCondition.status" placeholder="授权状态" style="width: 200px">
                    <Option v-for="item in statusArr" :value="item.value" :key="item.value">{{ item.name }}</Option>
                </Select>
            </FormItem>
            
            <FormItem>
                <DatePicker v-model="searchCondition.date" type="date" placeholder="授权有效期" style="width: 200px"></DatePicker>
            </FormItem>
            
            <FormItem>
                <Input v-model="searchCondition.detail" placeholder="被授权者姓名/电话/租客姓名/操作者" style="width: 200px" />
            </FormItem>

            <FormItem>
                <Button
                    type="primary"
                    @click="searchSub"
                    :loading="searchLoading">搜索</Button>
            </FormItem>
        </Form>-->

        <!-- 授权列表 -->
        <Card>
            <Table stripe border ref="selection" :columns="columns" :data="data" size="small" :loading="tableLoading"></Table>
        </Card>

        <!-- 列表操作按钮 -->
        <!-- <Card style="padding-bottom: 10px; background-color: white;">
            <Button type="primary" style="margin-right: 10px" @click="handleSelectAll">全选</Button>
            <Button type="primary" style="margin-right: 10px">冻结</Button>
            <Button type="primary" style="margin-right: 10px">解冻</Button>
            <Button type="primary" style="margin-right: 10px">删除</Button>
        </Card> -->

        <!-- 设置或者重置999的超级管理员密码弹窗 -->
        <Modal
            v-model="adminPasswordIsVisible"
            :mask-closable="false"
            :width="520"
            :title="title"
            @on-ok="ok('setPassword')"
            class-name="license-modal">
            <Form :model="formData"  :label-width="120"  ref="setPassword" :rules="formRules">
                <Row type="flex" align="middle" justify="center">
                    <Col span="16">
                        <FormItem label="请输入密码:" style="margin-top:24px" prop="password" >
                            <Input v-model="formData.password" placeholder="请输入6位的数字密码"></Input>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </Modal>

        <!-- 查看管理员密码 -->
        <Modal
            title="管理员密码"
            v-model="PasswordIsVisible"
            class-name="vertical-center-modal license-modal">
            {{adminPasswordContent}}
        </Modal>

        <!-- 删除密码 Modal-->
        <Modal
            title="删除授权记录"
            @on-ok="delPasswordRequest(delPasswordConfig.item)"
            v-model="delPasswordConfig.isDelPasswordIsVisible"
            class-name="vertical-center-modal license-modal">

            <div v-html="delPasswordConfig.content"></div>
        </Modal>

        <!-- 获取临时密码 -->
        <getActPwd :visible="getPwddayjsVisible" :lockDetail="lockDetail" @on-close="getPwddayjsVisible = false"></getActPwd>

        <!-- 新增授权 -->
        <sendPwd :lockDetail="lockDetail" :visible="addLicenseVisible" @on-close="closeAddLicense" :renterDetail="renterDetail" :isForce="isForce"/>

        <!-- 修改密码有效期 -->
        <changePwd :visible="visible" @on-close="closeSendPwd" @refresh="refresh" :passwordDetail="passwordDetail" :lockDetail="lock" :isAdmin="isAdmin" :isFinger="isFinger"></changePwd>

        <Modal v-model="isShowPermissionModal" title="新增授权" class-name="vertical-center-modal license-modal" :mask-closable="false" :closable="false">
            <!-- <div slot="header">
            </div> -->

            <p v-if="rolePermission['active_lease_permission']">根据公寓安全设置，租客入住后，禁止新增授权</p>
            <p v-else>权限受限，租客入住后如需新增授权，请联系商户超级管理员修改帐号所属角色的权限范围</p>

            <div slot="footer">
                <Button type="ghost" size="large" @click="isShowPermissionModal = false">取消</Button>
                <Button type="primary" size="large" @click="openGrantModal" v-if="rolePermission['active_lease_permission']">我已知悉风险，确定继续新增</Button>
            </div>
        </Modal>

    </div>
</template>

<script>
// import util from '@/libs/util';
import { http, api } from '@/libs/http'
import { mapState } from 'vuex'
import { NormalPasswordError } from '@/libs/const'
import changePwd from './changePwd.vue'
import sendPwd from './sendPwd.vue'
import getActPwd from './getActPwd.vue'
import dayjs from 'dayjs'
export default {
  name: 'room-licens',

  props: {
    lockDetail: {
      // 单个门锁设备详情
      required: true
    },
    isFromRenter: {
      // 是否是从租客详情列表打开
      default: false,
      type: Boolean
    },
    passwords: {
      // 授权密码
      type: Array
    },
    roomName: {
      // 房间名称
      type: String
    }
  },

  components: {
    changePwd,
    sendPwd,
    getActPwd
  },

  computed: {
    ...mapState({
      rolePermission: state => state.app.permission
    })
  },

  data () {
    return {
      isForce: false, // 强制获取密码
      isShowPermissionModal: false, // 是否展示权限弹窗
      tableLoading: false, // 考格是否加载
      renterDetail: {}, // 关联租客信息
      isD3OrT3: false, // 是否为三系门锁
      roomId: '', // 房间id
      lockId: '', // 门锁id
      hasGateway: true, // 门锁是否有网关，默认为有网关门锁
      isFinger: false, // 是否是指纹密码
      specialPwd: {
        // 默认为3000的列表数据
        id: 3000,
        pwdStatus: '已生效',
        time: '永久有效',
        name: '离线管理员',
        send_to: '',
        note: '添加成功',
        type: 1,
        _disabled: true
      },
      data: [], // table列表数据
      columns: [
        //     { // table表格配置（和data数据一一对应）
        //     type: 'selection',
        //     width: 30,
        //     align: 'center'
        // }
      ],
      selectAll: true,
      searchCondition: {
        // 筛选条件值
        addType: '', // 授权方式
        status: '', // 授权状态
        date: null, // 授权有效期
        detail: '' // 被授权者姓名/电话/租客姓名/操作者
      },
      statusArr: [], // 授权状态列表
      searchLoading: false, // 条件搜索按钮loading过渡
      title: '', // 密码重置或者设置弹窗标题
      adminPasswordIsVisible: false, // 管理员弹窗打开开关
      PasswordIsVisible: false, // 管理员密码查看弹窗开关
      delPasswordConfig: {
        isDelPasswordIsVisible: false,
        content: '确定删除该授权记录?',
        item: null,
        api: null
      },
      visible: false, // 修改密码有效期弹窗
      adminPasswordContent: '', // 管理员密码提示语句
      formData: {
        password: '' // 弹窗对应密码
      },
      lock: {}, // 门锁详情
      isAdmin: false, // 是否是管理员密码
      passwordDetail: {}, // 构建密码对象传changePwd组件
      formRules: {
        // 六位数字密码规则
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 6,
            message: '密码必须为6位数的数字',
            trigger: 'blur'
          }
        ]
      },
      buttons: [
        // 无网关指纹锁按钮展示
        {
          type: 'ghost',
          text: '冻结'
        },
        {
          type: 'error',
          text: '删除'
        },
        {
          type: 'success',
          text: '修改'
        }
      ],
      getPwddayjsVisible: false, // 获取临时密码Modal显隐状态
      addLicenseVisible: false // 新增授权modal显隐状态
    }
  },

  watch: {
    addLicenseVisible (value) {
      if (!value) {
        this.isForce = false
      }
    }
  },

  mounted () {
    this.getLockStatus() // 获取门锁状态（是否有网关，是否在线）
    this.initColumn() // 初始化表格数据
    this.initData() // 初始化表格数据
    this.$nextTick(() => {
      let maskArr = document.getElementsByClassName('license-modal')
      let len = maskArr.length
      for (let i = 0; i < len; i++) {
        maskArr[i].parentNode.getElementsByClassName(
          'ivu-modal-mask'
        )[0].style.zIndex = 1004
      }
    })
    // console.log('lockDetail=============>', this.lockDetail);
  },

  methods: {

    /**
        * 是否打开授权弹窗
        */
    openGrantModal () {
      this.isForce = true
      this.isShowPermissionModal = false
      this.addLicenseVisible = true
    },

    /**
         * 初始化数据
         */
    initData () {
      if (this.isFromRenter) {
        // 是来源于租客页面
        this.data = this.constructData(this.passwords, true)
      } else {
        // 来源于门锁自身请求
        this.getGrantList() // 获取授权数据
      }
    },

    /**
         *  刷新组件
         *  @param {Boolean} pos 刷新时是否清除之前数据
         */
    refresh (pos = false) {
      pos && (this.data = [])

      this.isFromRenter ? this.$emit('refresh') : this.getGrantList()
    },

    /**
         * 关闭修改密码有效期弹窗
         * @param {Boolean} pos
         */
    closeSendPwd (pos) {
      this.visible = pos
    },

    /**
         * 获取门锁授权记录
         */
    getGrantList () {
      this.tableLoading = true
      http.request(
        this,
        api.password_list,
        [this.roomId, this.lockId],
        null,
        (res, err) => {
          if (err || !res) {
            return
          }

          this.tableLoading = false
          this.data = this.constructData(res)
        }
      )
    },

    /**
         * 构造列表数据data
         * @param {Array} res 授权列表米啊么
         * @param {Boolean} isFromRenter 是否是从租客列表进入
         */
    constructData (res = [], isFromRenter = false) {
      let arr = []

      for (let key = 0; key < res.length; key++) {
        let {
          id,
          pwd_state,
          operation_stage,
          permission,
          name,
          send_to,
          operation,
          description,
          status,
          type,
          op_error,
          paas_fp_id,
          tenant_name = ''
        } = res[key] // 每一个列表项

        const pwdStatus = this.getPwdStatus(pwd_state, operation_stage)

        const time = this.getTime(permission, type)

        send_to = send_to || ''

        const note = this.getNote(
          operation,
          operation_stage,
          description,
          type
        )

        const obj = {
          id,
          pwdStatus,
          time,
          name,
          send_to,
          operation,
          note,
          status,
          type,
          operation_stage,
          description,
          op_error,
          paas_fp_id,
          end: permission.end,
          begin: permission.begin,
          tenant_name
        }

        if (this.hasGateway) {
          // 有网关门锁情况下id为999的密码确保第一个展示
          if (!isFromRenter && id === 999) {
            // 门锁内授权密码
            obj._disabled = true
            arr.unshift(obj)
          } else {
            if (id !== 3000) { // 确保有网关门锁没有3000的密码
              arr.push(obj)
            } else { // id 为3000的普通管理员密码,保证出现在第二个
              if (arr[0] && arr[0].id === 999) {
                arr.splice(1, 0, obj)
              } else {
                arr.unshift(obj)
              }
            }
          }
        } else {
          // 无网关情况下确保3000出现在第一个
          id !== 3000 ? arr.push(obj) : arr.unshift(obj)
        }
      }

      return arr
    },

    /**
         * 获取门锁状态 （是否门锁有无网关，是否在线）
         */
    getLockStatus () {
      let { parent, roomId, id, sn } = this.lockDetail

      this.hasGateway = parent !== 'GOD'
      this.roomId = roomId
      this.lockId = id
      this.isD3OrT3 = ['23', '24', '25', '26', '29'].includes(sn.substring(6, 8))

      this.lock = {
        roomId,
        device_id: id
      }
    },

    /**
         * 初始化Table表格数据
         */
    initColumn () {
      const arr = [
        {
          key: 'id',
          minWidth: 110,
          title: '授权编号',
          align: 'center'
        },
        { key: 'pwdStatus', minWidth: 40, title: '状态' },
        { key: 'time', minWidth: 200, title: '密码有效期' },
        { key: 'name', minWidth: 130, title: '被授权者信息' },
        { key: 'tenant_name', minWidth: 100, title: '关联租客' },
        { key: 'note', minWidth: 100, title: '备注' },
        { key: 'operation', minWidth: 180, title: '操作' }
      ]

      // 渲染密码和非密码
      arr[0].render = (h, params) => {
        const {
          row: { type, id, paas_fp_id }
        } = params

        const button = this.renderObj('default', false, false, true)
        const str = type === 1 ? '密码' : '指纹'
        const finalId = type === 1 ? id : paas_fp_id // 如果是指纹展示pass_id
        return h('div', [
          h('Button', button, str),
          h(
            'span',
            { style: { float: 'left', marginTop: '3px' } },
            finalId
          )
        ])
      }

      // 如果有错误的话出现可以提示错误的参数
      arr[5].render = (h, params) => {
        const {
          row: { note, op_error, type, description }
        } = params
        const hasError = note.indexOf('失败') !== -1

        if (hasError) {
          const error = type === 2 ? op_error : `${Number(description)}:${NormalPasswordError[Number(description)] && NormalPasswordError[Number(description)].description}`
          // return h(
          //     'Tooltip',
          //     {
          //         props: {
          //             placement: 'top',
          //             content:
          //                 type === 2
          //                     ? op_error
          //                     : NormalPasswordError[Number(description)] &&
          //                       NormalPasswordError[
          //                           Number(description)
          //                       ].description
          //         },
          //         style: { cursor: 'pointer' }
          //     },
          //     [h('span', { style: { color: '#ff0000' } }, note)]
          // );
          return h('span', { style: { color: '#ff0000' } }, `${note} (${error})`)
        } else {
          return h('span', note)
        }
      }

      arr[3].render = (h, params) => {
        const {
          row: { name, send_to }
        } = params
        return h('span', name + ' ' + send_to)
      }

      // 渲染操作按钮
      arr[arr.length - 1].render = (h, params) => {
        let {
          row: {
            pwdStatus,
            status,
            operation_stage,
            id,
            operation,
            send_to,
            name,
            end,
            type,
            begin
          }
        } = params

        if (id > 3000) { // 如果为普通激活码密码
          const isToday = dayjs().endOf('day').valueOf() - dayjs(begin).valueOf()
          // console.log(id, begin, dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'), dayjs(begin).valueOf().format('YYYY-MM-DD HH:mm:ss'));
          if (isToday >= 0 && isToday <= 86399999) {
            return h('p', {style: {color: '#f00'}}, '离线密码当天不可变更')
          }
        }

        if (id === 3000) { // 普通管理员密码
          // id为3000的密码
          let buttonOne = this.renderObj('ghost', operation_stage === 1)
          buttonOne.on.click = () => {
            // 修改
            this.passwordDetail = {
              name,
              phonenumber: send_to
            }
            this.isAdmin = true
            this.visible = true
          }

          const renderObj = [h('Button', buttonOne, pwdStatus === '未设置' ? '设置' : '修改')]

          if (this.hasGateway && pwdStatus !== '未设置') { // 有网关情况下普通管理员密码也需要有失效按钮
            const buttonTwo = this.renderObj('error', operation_stage === 1)

            buttonTwo.on.click = () => {
              this.passwordBeUseless(3000)
            }

            renderObj.push(h('Button', buttonTwo, '失效'))
          }

          return h('div', renderObj)
        }

        if (this.hasGateway) {
          // 有网关门锁
          if (id === 999) {
            // id为999的密码
            // const str = status === 0 ? '设置' : '重置';
            const str = pwdStatus === '未设置' ? '设置' : '修改'

            let buttonOne = this.renderObj(
              'ghost',
              operation_stage === 1
            ) // 设置或者重置按钮
            let buttonTwo = this.renderObj(
              'success',
              !status || operation_stage === 1
            ) // 查看管理员密码按钮

            let buttonThree = this.renderObj(
              'error',
              !this.isD3OrT3 || operation_stage === 1 || pwdStatus === '未设置'
            ) // 非T3/D3 不显示失效按钮

            // 设置或者重置按钮绑定事件
            buttonOne.on.click = () => {
              this.title = `密码${str}`
              this.adminPasswordIsVisible = true
            }

            // 查看管理员密码
            buttonTwo.on.click = () => {
              this.getRoomAdminPassword()
            }

            buttonThree.on.click = () => { // 有网关并且为T3或者D3失效
              this.passwordBeUseless(999)
            }

            return h('div', [
              h('Button', buttonOne, str),
              h('Button', buttonTwo, '查看'),
              h('Button', buttonThree, '失效')
            ])
          } else {
            // 普通密码和激活码密码
            const str = pwdStatus === '已冻结' ? '解冻' : '冻结'

            let buttonOne = this.renderObj(
              'ghost',
              (pwdStatus !== '已生效' &&
                                pwdStatus !== '已冻结') ||
                                operation_stage === 1
            )

            buttonOne.on.click = () => {
              this.passwordFrozenOrUnfrozen(id, str, type)
            }

            let buttonTwo = this.renderObj(
              'error',
              operation_stage === 1,
              operation_stage === 1 && operation === 2
            )

            buttonTwo.on.click = () => {
              // 删除
              this.delPassword({ id, type })
            }

            let buttonThree = this.renderObj(
              'success',
              (pwdStatus !== '已生效' &&
                                pwdStatus !== '已冻结') ||
                                operation_stage === 1
            )

            buttonThree.on.click = () => {
              // 修改密码有效期

              if (send_to === '' && type === 1) {
                // 有网关非指纹密码必须要有电话号码
                this.$Message.warning(
                  '该密码非云服务器生成，无法修改'
                )
                return
              }

              this.passwordDetail = {
                country_code: '86',
                name,
                phonenumber: send_to,
                id,
                pwdStartTime: id > 3000 ? new Date(begin) : new Date(),
                pwdEndTime: new Date(end),
                pwdType: id > 3000 ? 2 : 1
              }

              if (type === 1) {
                // 设置是否打开指纹弹窗
                this.isFinger = false
              } else {
                this.isFinger = true
                this.passwordDetail.pwdType = 1
              }

              this.isAdmin = false
              this.visible = true
            }

            return h('div', [
              h('Button', buttonOne, str),
              h('Button', buttonTwo, '删除'),
              h('Button', buttonThree, '修改')
            ])
          }

          // if (id === 3000) {
          //     const button = this.renderObj(
          //         'error',
          //         operation_stage === 1
          //     );

          //     button.on.click = () => { // 有网关并且为T3或者D3失效
          //         this.passwordBeUseless(3000);
          //     };

          //     adminRender.push(h('Button', button, '失效'));
          // }
        } else {
          // 无网关门锁

          // 对象数组深拷贝，
          let buttons =
                        type === 1
                          ? JSON.parse(JSON.stringify(this.buttons.slice(1, 2)))
                          : JSON.parse(JSON.stringify(this.buttons.slice(0)))

          if (buttons.length === 1) {
            // 非指纹门锁
            buttons[0].special = true
            buttons[0].id = id
          }

          return h(
            'div',
            buttons.map((value, index) => {
              return h(
                'Button',
                this.renderSpecialButton(value),
                value.text
              )
            })
          )
        }

        // if (adminRender.length) {
        //     return h('div', adminRender)
        // }
      }

      let res = arr.map(value => {
        return { ...value, align: 'center' }
      })
      this.columns.push(...res)
    },

    /**
         * @param {Object} type 按钮类型， special 是否是非指纹密码
         */
    renderSpecialButton ({ type, special, id }) {
      let button = this.renderObj(type, false)
      button.on.click = () => {
        this.delPassword({ type: special ? 1 : 2, id })
      }
      return button
    },

    /**
        * 密码失效
        * @param {Number} id 密码失效
        */
    passwordBeUseless (id) {
      this.$Modal.confirm({
        title: '请确认',
        content: '操作会让该密码失效,是否继续操作？',
        okText: '是',
        cancelText: '取消',
        onOk: () => {
          this.delPasswordConfig.api = [999, 3000].includes(id) ? api.password_admin_password_delete : api.password_del // 如果为999或者3000的密码失效调用新接口
          this.delPasswordRequest({id})
        }
      })
    },

    /**
         * 是否删除密码
         * @param {Object} obj 密码id 包含密码id，密码类型， 是否包含网关
         */
    delPassword (obj = {}) {
      const { id, type } = obj
      let content
      this.delPasswordConfig.item = obj

      if (!this.hasGateway) {
        // 如果为无网关门锁

        if (type === 1) {
          // 非指纹密码
          content = `<p>1.按#键，门锁“滴”一声提示;按*键，门锁“滴”一声提示。</p>
                               <p>2.输入“02”，门锁“滴滴”两声提示。</p>
                               <p>3.输入要删除密码编号 ( <strong> ${id} </strong> )，门锁“滴滴”两声提示。</p>
                               <p>4.输入管理员密码或工作人员密码:正确，门锁“都啦咪”响，删除成功;错误，低声“滴”响 0.6 秒，屏幕灭，删除失败。</p>`
        } else {
          // 指纹密码
          content = '<p>请通过App执行此操作</p>'
        }
      } else {
        // 有网关门锁
        const finallyApi =
                    type === 1 ? api.password_del : api.finger_password_del
        this.delPasswordConfig.api = finallyApi
        content = `确定删除编号为 <strong> ${id} </strong> 的授权记录?`
      }

      this.delPasswordConfig.content = content
      this.delPasswordConfig.isDelPasswordIsVisible = true
    },

    delPasswordRequest (obj) {
      if (!this.delPasswordConfig.api) {
        return
      }
      http.request(
        this,
        this.delPasswordConfig.api,
        [this.roomId, this.lockId, obj.id],
        null,
        res => {
          if (res) {
            this.$Message.success('删除指令已下发')
            this.refresh()
          }
        }
      )
    },

    /**
         * @param {String} buttonType 按钮类型
         * @param {Boolean} flag 按钮是否隐藏
         * @param {Boolean} isDisplay 按钮是否可以点击,默认可以点击
         * @return {Object} 返回render对象
         */
    renderObj (buttonType, flag, isDisplay = false, isLeft = false) {
      return {
        props: {
          type: buttonType,
          size: 'small',
          disabled: isDisplay
        },
        style: {
          marginRight: '5px',
          display: flag ? 'none' : 'initial',
          float: isLeft ? 'left' : 'initial'
        },
        on: {}
      }
    },

    /**
         * 冻结或者解冻密码
         * @param {Number} id 密码id
         * @param {String} str 冻结或者解冻
         * @param {Number} type type => 1 普通密码 type => 2 指纹密码
         */
    passwordFrozenOrUnfrozen (id, str, type) {
      let finalApi

      if (type === 1) {
        finalApi =
                    str === '冻结'
                      ? api.password_frozen
                      : api.password_unfrozen
      } else {
        finalApi =
                    str === '冻结'
                      ? api.finger_password_frozen
                      : api.finger_password_unfrozen
      }

      http.request(
        this,
        finalApi,
        [this.roomId, this.lockId, id],
        null,
        (res, err) => {
          if (err) {
            return
          }

          this.$Message.success(`恭喜您,${str}指令已下发`)
          this.refresh()
        }
      )
    },

    /**
         * 前端校验管理员密码格式
         * @param {表单名} name
         */
    ok (name) {
      this.$refs[name].validate(valid => {
        const password = this.formData.password

        if (!valid) {
          this.$Message.warning('管理员密码必须为六位数的数字')
          this.formData.password = ''
          return
        }

        const arr = password.split('')
        const pos = arr.every(value => {
          return value >= '0' && value <= '9'
        })

        if (!pos) {
          this.formData.password = ''
          this.$Message.warning('密码中不能包含除数字以外的字符')
          return
        }

        this.resetRoomAdminPassword(this.title === '密码修改', password)
      })
    },

    /**
         * 重置或者设置超级管理员密码
         * @param {Boolean} flag true代表密码重置，false代表密码设置
         * @param {String} password 密码
         */
    resetRoomAdminPassword (isUpdate, password) {
      const setApi = isUpdate
        ? api.password_admin_update
        : api.password_admin_add

      const params = {
        name: '管理员密码',
        is_default: true,
        permission_status: 1,
        password: password
      }

      http.request(
        this,
        setApi,
        [this.roomId, this.lockId],
        params,
        (res, err) => {
          if (err || !res) {
            return
          }

          this.$Message.success(
            `恭喜您,管理员密码${isUpdate ? '更新' : '设置'}指令已下发`
          )
        }
      )
    },

    /**
         * 查看管理员密码
         */
    getRoomAdminPassword () {
      http.request(
        this,
        api.password_admin,
        [this.roomId, this.lockId],
        null,
        (res, err) => {
          if (err || !res) {
            return
          }

          const { password } = res

          if (password) {
            this.PasswordIsVisible = true
            this.adminPasswordContent = `您的管理员密码:${password} (若管理密码在本地被修改，此密码值将无效，可通过重置设置新密码)`
          } else {
            this.$Message.warning('管理员密码正在设置中请稍后再试')
          }
        }
      )
    },

    /**
         * 获取普通门锁密码的状态
         */
    getPwdStatus (pwd_state, operation_stage) {
      let result = ''
      pwd_state =
                typeof pwd_state === 'string' ? Number(pwd_state) : pwd_state

      switch (pwd_state) {
        case 0:
          result = '未设置'
          break
        case 1:
          // switch (operation_stage) {
          //     case 1:
          //         result = '下发失败'
          //         break
          //     case 2:
          //     case 3:
          //         result = '已失效'
          //         break
          //     default:
          //         result = '未知'
          //         break
          // }
          result = '不可用'
          break
        case 2:
          result = '已生效'
          break
        case 3:
          result = '将生效'
          break
        case 4:
          result = '已过期'
          break
        case 5:
          result = '已冻结'
          break
        default:
          result = '未知'
          break
      }

      return result
    },

    /**
         * 返回时间字符串比如 2018-06-13至2018-06-28
         * @param {Object} time
         */
    getTime ({ begin, end }, type) {
      if (!begin) {
        return '永久有效'
      }

      // if (type === 1) {
      //     begin = begin * 1000
      //     end = end * 1000
      // }
      return `${dayjs(begin).format('YYYY-MM-DD HH:mm')}至${dayjs(
        end
      ).format('YYYY-MM-DD HH:mm')}`
    },

    /**
         * 获取备注（如果没有问题返回数据比如：添加成功， 如果添加失败在之前加一个数组比如5101:添加失败）
         * "5101": "服务器超时",
         * "5102": "设备操作成功，但数据库执行出错",
         * "5103": "门锁在执行对应服务时出现错误",
         * "5104": "密码内容相似(连续四位及以上相同)",
         * "5105": "锁内已经存在一个该序号的密码",
         * "5106": "密码无效，permission内容无效",
         * "5107": "密码池满，无法添加新密码",
         * "5108": "门锁本地无此密码记录，无法响应",
         * "5199": "门锁本地被重置"
         * @param {Number} type 密码类型，1为普通门锁密码，2为指纹门锁密码
         * 当门锁为普通门锁的时候description为1000的时候为正常，其他的时候都为不正常，需要显示
         * 当门锁为指纹密码的时候，不存在description这一个字段，不管如果都不显示状态码
         */
    getNote (operation, operation_stage, description, type) {
      let operate
      let operateResult

      if (!operation) { // 不存在返回空字符串
        return ''
      }

      switch (operation) {
        case 1:
          operate = '添加'
          break
        case 2:
          operate = '删除'
          break
        case 3:
          operate = '更新'
          break
        case 4:
          operate = '冻结'
          break
        case 5:
          operate = '解冻'
          break
        default:
          operate = '未知'
      }

      switch (operation_stage) {
        case 1:
          operateResult = '进行中'
          break
        case 2:
          operateResult = '失败'
          break
        case 3:
          operateResult = '成功'
          break
        default:
          operateResult = '未知'
          break
      }

      return operate + operateResult
    },

    // 全选
    handleSelectAll () {
      this.$refs.selection.selectAll(this.selectAll)
      this.selectAll = !this.selectAll
    },

    // 授权列表条件查找
    searchSub () {
      // searchCondition: { // 筛选条件值
      //     addType: "", // 授权方式
      //     status: "", // 授权状态
      //     date: null, // 授权有效期
      //     detail: "", // 被授权者姓名/电话/租客姓名/操作者
      // }
      this.searchLoading = true
      setTimeout(() => {
        this.searchLoading = false
      }, 1000)
      // http.request(this, api.???, [???], null, (res, err) => {
      //         if (err) {
      //             return this.$Message.error('Fail!');
      //         }

      //         // 请求接口，获取数据，替换this.data数组
      //         this.data = res

      //         // 重置全选状态
      //         this.$refs.selection.selectAll(false);
      //         this.selectAll = false;
      //     }
      // )
    },

    // 新增授权弹窗
    addLicense () {
      http.request(
        this,
        api.room_lock_pre_add_password,
        [this.roomId, this.lockId],
        null,
        (res, err) => {
          if (err || !res) {
            return
          }

          const { permission_denied } = res

          if (!permission_denied) { // 如果足够的话不足的话直接弹出弹窗
            this.addLicenseVisible = true
          } else {
            this.isShowPermissionModal = true
          }
          this.renterDetail = res
        }
      )
    },

    // 新增授权modal关闭
    closeAddLicense () {
      this.addLicenseVisible = false
    }

    // 密码有效期开始时间选择
    // addLicenseTimeChange(res, type) {
    //     console.log(res, type)
    //     console.log(this.addLicenseData.addLicenseStartTime);
    // }
  }
}
</script>

<style lang='less' scoped>
.hide {
    display: none !important;
}
.title {
    padding-top: 15px;
    font-size: 22px;
    font-weight: 800;
    text-align: center;
}
.tableSetBtn {
    margin: 8px 0;
    text-align: right;
}
.tableSetBtn button {
    margin: 0 10px;
}
.noPwd {
    position: absolute;
    top: 14px;
    left: 50%;
}
</style>

<style>
.license-modal {
    z-index: 9999 !important;
}
</style>